<template>
  <div style="display: inline">
    <el-form-item label="工序">
      <el-select
        v-model="searchParam.processId"
        placeholder="请选择工序"
        clearable
        filterable
        @change="processChange"
      >
        <el-option
          v-for="item in processList"
          :key="item.id"
          :label="item.processCode"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="生产线">
      <el-select
        v-model="searchParam.equipId"
        placeholder="请选择生产线"
        clearable
        filterable
        @change="equipChange"
      >
        <el-option
          v-for="item in equipList"
          :key="item.id"
          :label="item.equipCode"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="项目描述">
      <el-select
        v-model="searchParam.projectId"
        placeholder="请选择项目描述"
        clearable
        filterable
        @change="projectChange"
      >
        <el-option
          v-for="item in projectList"
          :key="item.id"
          :label="item.projectName"
          :value="item.id"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="产品型号">
      <el-select
        v-model="searchParam.productId"
        placeholder="请选择产品型号"
        clearable
        filterable
        :filter-method="customFilter"
        @change="productChange"
      >
        <el-option
          v-for="item in filteredOptions"
          :key="item.id"
          :label="item.productCode"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
  </div>
</template>

<script setup lang="ts">
import { ElInput } from "element-plus";
import request from "@/utils/request";
import {
  getMdminspectiontoolApi,
  getMdmProcessEquipApi,
  getMdmProcessProjectApi,
  getMdmproductinfosApi,
  getMdmprojectinfosApi,
  getSpecificListApi,
  getMdmprocessListApi,
  getMdmProcessEquipApi1,
} from "@/utils/commonData";
import _ from "lodash-es";

defineOptions({
  name: "PCMMONITORINGCOMMONSEARCH",
  inheritAttrs: false,
});
const props = defineProps({
  data: {
    // v-model 绑定
    type: Object,
    default: () => {},
  },
});

const emit = defineEmits(["update:data", "changeSearch"]);

// 创建响应式副本
const searchParam = ref({
  processId: "",
  processCode: "",
  processName: "",
  equipId: "",
  equipCode: "",
  equipName: "",
  projectId: "",
  projectCode: "",
  projectName: "",
  productId: "",
  productCode: "",
  productName: "",
});

// 监听父组件传入的 data 变化
watch(
  () => props.data,
  (newVal) => {
    console.log("jinlai", newVal.value);

    searchParam.value.processId = newVal.processId;
    searchParam.value.processCode = newVal.processCode;
    searchParam.value.processName = newVal.processName;
    searchParam.value.equipId = newVal.equipId;
    searchParam.value.equipCode = newVal.equipCode;
    searchParam.value.equipName = newVal.equipName;
    searchParam.value.projectId = newVal.projectId;
    searchParam.value.projectCode = newVal.projectCode;
    searchParam.value.projectName = newVal.projectName;
    searchParam.value.productId = newVal.productId;
    searchParam.value.productCode = newVal.productCode;
    searchParam.value.productName = newVal.productName;
    if (
      searchParam.value.processId == "" &&
      searchParam.value.equipId == "" &&
      searchParam.value.projectId == "" &&
      searchParam.value.productId == ""
    ) {
      // -----------------------
      // 获取项目列表
      getProjectList({});

      // 获取工序列表
      getProcessList({});

      // 获取设备列表
      getEquipList({});

      // 获取产品型号列表
      getProductList({});
    }
  },
  { deep: true }
);

// 统一处理变化事件
const handleChange = (field, value) => {
  // 触发 v-model 更新
  emit("update:data", { ...searchParam.value });
};

// 获取项目列表
const projectList = ref<any>([]);
async function getProjectList(params: Object) {
  projectList.value = (await getMdmprojectinfosApi(params)) || [];
  oldProjectList.value = projectList.value;
}

async function projectChange(id: string) {
  // 项目->工序->设备
  // 当 改变项目时 所有清空并且 设备 产品型号 工序 都根据项目id重新获取下拉列表

  if (id) {
    const current: any =
      projectList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.projectCode = current.projectCode || "";
    searchParam.value.projectName = current.projectName || "";
    if (searchParam.value.processId == "") {
      searchParam.value.equipId = "";
      searchParam.value.equipCode = "";
      searchParam.value.processId = "";
      searchParam.value.processCode = "";
      searchParam.value.processName = "";
      searchParam.value.productId = "";
      searchParam.value.productCode = "";
      searchParam.value.productName = "";
      // 根据项目获取产品型号
      getPjtPduList(id);
    }
    // 通过项目查询工序
    processList.value =
      (await getMdmProcessProjectApi({ projectId: id })) || [];
    // 设备 全部
    getEquipList({});
  } else {
    searchParam.value.projectCode = "";
    searchParam.value.projectName = "";
    getEquipList({});
    getProcessList({});
  }

  getProductList({ projectId: id });
  emit("changeSearch", searchParam.value);
}

// 获取工序列表
const processList = ref<any>([]);
async function getProcessList(id: string) {
  processList.value = (await getMdmprocessListApi({})) || [];
  oldProcessList.value = processList.value;
}

async function processChange(id: string) {
  // 项目->工序->设备
  // 当 改变工序时 一定清空设备数据 重新获取设备下拉  判断是否存在项目  有的话不清空也不清空列表 没有说明一开始就选工序,没有选项目 清空项目加获取项目列表
  /*
   */
  //
  //  设备 产品型号 工序 都根据项目id重新获取下拉列表

  searchParam.value.equipId = "";
  searchParam.value.equipCode = "";
  searchParam.value.equipName = "";
  if (id) {
    const current: any =
      processList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.processCode = current.processCode || "";
    searchParam.value.processName = current.processName || "";
    if (searchParam.value.projectId != "") {
      equipList.value = (await getMdmProcessEquipApi({ processId: id })) || [];
    } else {
      // 根据工序查项目 接口暂定
      getPcePjeList(id);
      searchParam.value.projectId = "";
      searchParam.value.projectCode = "";
      searchParam.value.projectName = "";
      equipList.value = (await getMdmProcessEquipApi({ processId: id })) || [];
    }
  } else {
    // 当工序清空时 判断项目 是否有值 设备显示全部
    if (searchParam.value.projectId != "" && searchParam.value.equipId != "") {
      searchParam.value.processCode = "";
    } else {
      //
      getEquipList({});
      getProductList({});
      getProcessList({});
    }
  }
  emit("changeSearch", searchParam.value);
}

// 获取产品型号列表
const productList = ref<any>([]);
const filteredOptions = ref<any>([]);
async function getProductList(params) {
  productList.value = (await getMdmproductinfosApi(params)) || [];
  oldProductList.value = productList.value;
  filteredOptions.value = [...productList.value];
}

// 使用 debounce 包装过滤方法
const customFilter = _.debounce((query: any) => {
  if (!query) {
    filteredOptions.value = [...productList.value];
    return;
  }
  filteredOptions.value = productList.value.filter((option: any) =>
    option.productCode.toLowerCase().includes(query.toLowerCase())
  );
}, 300); // 延迟 300ms

function productChange(id: string) {
  if (id) {
    const current: any =
      productList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.productCode = current.productCode || "";
    searchParam.value.productName = current.productName || "";
    getEquipList({});
    // --
    // 根据产品 获取获取项目
    getProPjeList(id);
    // 获取完之后  在获取工序列表
  } else {
    searchParam.value.productCode = "";
    searchParam.value.productName = "";
  }
  emit("changeSearch", searchParam.value);
}

// 通过工序查询设备列表
const equipList = ref(<any>[]);
async function getEquipList(params: Object) {
  equipList.value = (await getMdmProcessEquipApi1(params)) || [];
  oldEquipList.value = equipList.value;
}

function equipChange(id: string) {
  // 项目->工序->设备
  // 当 设备改变时  获取 项目和工序的名称赋值 及项目和工序及下拉数据 并且改变自身的下拉列表
  // ------------------------------------------------------------------------------------------------------------------------ 设备后续 再写

  // searchParam.value.projectId = "";
  // searchParam.value.projectCode = "";
  // searchParam.value.processName = "";
  // searchParam.value.productId = "";
  // searchParam.value.productCode = "";
  // searchParam.value.processId = "";
  // searchParam.value.processCode = "";
  // searchParam.value.processName = "";
  if (id) {
    const current: any =
      equipList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.equipCode = current.equipCode || "";
    searchParam.value.equipName = current.equipName || "";
    getEuqPocList(id);
    if (
      searchParam.value.projectId == "" ||
      searchParam.value.processId == ""
    ) {
      // 根据设备获取 项目id及工序id 并获取项目下拉列表及工序下拉列表  更新自身列表
    }
  } else {
    searchParam.value.equipCode = "";
    searchParam.value.equipName = "";
  }
  emit("changeSearch", searchParam.value);
}

// 根据项目获取产品型号
const getPjtPduList = async (e) => {
  await request({
    url: `/mdm/mdmproductinfo/getList/${e}`,
    method: "get",
  }).then((res) => {
    if (res.data) {
      productList.value = res.data;
    }
  });
};
// 根据工序id查询项目
const getPcePjeList = async (e) => {
  await request({
    url: `/eam/mdmprojectprocess/getList/${e}`,
    method: "get",
  }).then((res) => {
    if (res.data) {
      projectList.value = res.data;
      let mm = [];
      oldProjectList.value.forEach((item) => {
        projectList.value.forEach((item1) => {
          if (item.id == item1.projectId) {
            mm.push(item);
          }
        });
      });
      projectList.value = mm;
      if (projectList.value.length == 1) {
        searchParam.value.projectId = projectList.value[0].id;
        searchParam.value.projectCode = projectList.value[0].projectCode;
        searchParam.value.projectName = projectList.value[0].projectName;
      }
    }
  });
};
// 根据设备id查询工序
const getEuqPocList = async (e) => {
  await request({
    url: `/mdm/mdmprocessequip/getProcessList/${e}`,
    method: "get",
  }).then(async (res) => {
    if (res.data) {
      processList.value = res.data;
      searchParam.value.processId = res.data[0].id;
      searchParam.value.processName = res.data[0].processName;
      searchParam.value.processCode = res.data[0].processCode;
      getPcePjeList(searchParam.value.processId);
      equipList.value =
        (await getMdmProcessEquipApi1({
          processId: searchParam.value.processId,
        })) || [];
    }
  });
};

// 根据产品id查询项目
const getProPjeList = async (e) => {
  await request({
    url: `/mdm/mdmproductinfo/projectList/${e}`,
    method: "get",
  }).then(async (res) => {
    if (res.data) {
      projectList.value = [];
      projectList.value[0] = res.data;
      // projectList.value[0].id = res.data.projectId;

      let mm = [];
      oldProjectList.value.forEach((item) => {
        projectList.value.forEach((item1) => {
          if (item.id == item1.projectId) {
            mm.push(item);
          }
        });
      });
      projectList.value = mm;

      searchParam.value.projectId = res.data.projectId;
      searchParam.value.projectName = res.data.projectName;
      searchParam.value.projectCode = res.data.projectCode;
      processList.value =
        (await getMdmProcessProjectApi({
          projectId: searchParam.value.projectId,
        })) || [];
      getEquipList({});
    }
  });
};

let oldProjectList = ref([]);
let oldProcessList = ref([]);
let oldEquipList = ref([]);
let oldProductList = ref([]);

onMounted(() => {
  // -----------------------
  // 获取项目列表
  getProjectList({});

  // 获取工序列表
  getProcessList({});

  // 获取设备列表
  getEquipList({});

  // 获取产品型号列表
  getProductList({});
});
</script>
